﻿using LYR_RPA.Properties;
using LYR_RPA.service;
using LYR_RPA.utils;
using LYR_RPA.views.ui;
using System;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Management;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows;
using System.Windows.Forms;
using System.Windows.Threading;

namespace LYR_RPA
{
    /// <summary>
    /// App.xaml 的交互逻辑
    /// </summary>


    public partial class App : System.Windows.Application
    {
        public static HomeWindow HomeWindow;
        
        private WebSocketClient WebSocketClient;
        //托盘
        private NotifyIcon trayIcon;
        //托盘菜单
        private ContextMenuStrip trayMenu;
        public static readonly string RobotPath = "C:\\Program Files (x86)\\UiPath\\Studio\\UiRobot.exe";
        //互斥体名称
        private const string MutexName = "LYR-RPAMutex";
        //互斥体，用于判断是否有新的程序启动
        private Mutex mutex;
        
        private const int WM_SHOWME = 0x8000;
        [DllImport("user32.dll")]
        private static extern bool PostMessage(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam);

        [DllImport("user32.dll")]
        private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

        /*
         * 连接服务端
         */
        protected override void OnStartup(StartupEventArgs e)
        {
            // 注册全局异常处理事件
            DispatcherUnhandledException += App_DispatcherUnhandledException;
            bool createdNew;
            mutex = new Mutex(true, MutexName, out createdNew);

            if (!createdNew)
            {
                ActivateExistingInstance();
                // 如果互斥体已存在，说明已经有另一个实例在运行，直接退出应用程序
                Environment.Exit(0);
            }

            base.OnStartup(e);
            //托盘初始化
            InitializeTrayIcon();

            if (string.IsNullOrEmpty(Settings.Default.RobotPath))
            {
                Settings.Default.RobotPath = RobotPath;
                Settings.Default.Save();
            }
            var searcher = new ManagementObjectSearcher("SELECT  UUID FROM Win32_ComputerSystemProduct");

            foreach (var item in searcher.Get())
            {
                Console.WriteLine("Device ID: " + item["UUID"]);
                Settings.Default.ID = item["UUID"].ToString();
                Settings.Default.Save();
                break;
            }
            WebSocketClient=WebSocketClient.Instance;
            if (!string.IsNullOrEmpty(Settings.Default.ServerAddress) && !string.IsNullOrEmpty(Settings.Default.Port))
            {
                Console.WriteLine("初始化连接");
                _ = WebSocketClient.Connect();
            }
            
        }

        /*
         * 全局异常捕捉
         */
        private void App_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
        {
            //Console.WriteLine(e.Exception.StackTrace);
            //string errerPath= Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\LYR_RPA\\errer.txt";
            //File.AppendAllText(errerPath,"  异常发生日期："+DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")+"\n\r"+ e.Exception.StackTrace+"\n\r");
            
            // 标记异常已处理，避免应用程序终止
            e.Handled = true;
        }

        //激活已启动的窗口界面显示
        private void ActivateExistingInstance()
        {
            var process = Process.GetCurrentProcess();
            var processes = Process.GetProcessesByName(process.ProcessName);
            foreach (var p in processes)
            {
                
                if (p.Id != process.Id)
                {
                    
                    var hwnd = FindProcessMainWindowHandle(p);
                    if (hwnd != IntPtr.Zero)
                    {
                        PostMessage(hwnd, WM_SHOWME, IntPtr.Zero, IntPtr.Zero);
                        break;
                    }
                }
            }
        }

        // 查找进程的主窗口句柄
        private IntPtr FindProcessMainWindowHandle(Process process)
        {
            IntPtr hwnd = IntPtr.Zero;

            if (process != null && !process.HasExited)
            {
                hwnd = process.MainWindowHandle;
            }
            return hwnd;
        }

        /*
         * 图标初始化
         */
        private void InitializeTrayIcon()
        {
            // 初始化托盘菜单
            trayMenu = new ContextMenuStrip();
            // 获取连接图标资源流
            // 创建 Bitmap 对象
            Bitmap connectBitmap = new Bitmap(GetResourceStream(new Uri("pack://application:,,,/LYR-RPA;component/resources/img/connect.png")).Stream);
            Bitmap quitBitmap = new Bitmap(GetResourceStream(new Uri("pack://application:,,,/LYR-RPA;component/resources/img/quit.png")).Stream);
            Bitmap stopBitmap = new Bitmap(GetResourceStream(new Uri("pack://application:,,,/LYR-RPA;component/resources/img/stop.png")).Stream);

            // 创建 ToolStripMenuItem，菜单项标题，点击事件，图标
            ToolStripMenuItem connectMenuItem = new ToolStripMenuItem("重新连接", null, TrayMenuConnect_Click)
            {
                Image = connectBitmap,
                Height = 100
            };
            ToolStripMenuItem stopMenuItem = new ToolStripMenuItem("结束执行", null, TrayMenuStop_Click)
            {
                Image = stopBitmap,
                Height = 100
            };
            ToolStripMenuItem quitMenuItem = new ToolStripMenuItem("退出程序", null, TrayMenuExit_Click)
            {
                Image = quitBitmap,
                Height = 100
            };

            // 添加到托盘菜单
            trayMenu.Items.Add(connectMenuItem);
            trayMenu.Items.Add(stopMenuItem);
            trayMenu.Items.Add(quitMenuItem);

            // 初始化托盘图标
            trayIcon = new System.Windows.Forms.NotifyIcon
            {
                Icon = new Icon(GetResourceStream(new Uri("pack://application:,,,/LYR-RPA;component/resources/img/icon.ico")).Stream),
                Visible = true,
                ContextMenuStrip = trayMenu
            };
            //托盘点击事件
            trayIcon.MouseClick += TrayIcon_Click;
        }
        /*
         * 点击退出菜单项
         */
        private void TrayMenuExit_Click(object sender, EventArgs e)
        {
            // 关闭应用程序
            WebSocketClient.Close();
            
            
            // 隐藏图标并释放资源
            trayIcon.Visible = false;
            trayIcon.Dispose();

            // 关闭应用程序
            Current.Shutdown();
        }
        
        /*
         * 点击退出菜单项
         */
        private void TrayMenuStop_Click(object sender, EventArgs e)
        {
            CommonUtils.CloseProcess("UiPath.Executor");
        }

        /*
         * 点击重新连接后的菜单项
         */
        private void TrayMenuConnect_Click(object sender, EventArgs e)
        {
            //重新连接
            _ = WebSocketClient.Connect();
        }

        /*
         * 托盘点击后显示窗口
         */
        private void TrayIcon_Click(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                ShowMainWindow();
            }
        }
        /*
         * 显示窗口方法
         */
        private void ShowMainWindow()
        {
            
            HomeWindow.Show();
            HomeWindow.WindowState = WindowState.Normal;
        }
        /*
         * 释放托盘资源
         */
        protected override void OnExit(ExitEventArgs e)
        {
            // 释放互斥体和系统托盘资源
            mutex.Dispose();
            if (trayIcon != null)
            {
                trayIcon.Dispose();
            }

            base.OnExit(e);
        }
    }
}
